<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>优惠券管理系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#FF7D00',
                        success: '#00B42A',
                        danger: '#F53F3F',
                        warning: '#FF7D00',
                        info: '#86909C',
                        light: '#F2F3F5',
                        dark: '#1D2129'
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .coupon-card {
                @apply relative overflow-hidden rounded-lg shadow-md transition-all duration-300 hover:shadow-lg;
            }
            .coupon-card::before {
                content: '';
                @apply absolute top-0 left-0 w-full h-full bg-gradient-to-r from-primary/10 to-secondary/10 -z-10;
            }
            .coupon-status {
                @apply absolute top-3 right-3 px-2 py-1 rounded-full text-xs font-medium;
            }
            .btn-primary {
                @apply bg-primary hover:bg-primary/90 text-white font-medium rounded-lg px-4 py-2 transition-all duration-300;
            }
            .btn-secondary {
                @apply bg-white border border-primary text-primary hover:bg-primary/5 font-medium rounded-lg px-4 py-2 transition-all duration-300;
            }
            .input-field {
                @apply border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-300;
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-inter">
<div class="max-w-6xl mx-auto px-4 py-8">
    <!-- 顶部导航栏 -->
    <header class="mb-10">
        <div class="flex justify-between items-center">
            <div class="flex items-center space-x-2">
                <i class="fa fa-ticket text-primary text-3xl"></i>
                <h1 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold text-dark">优惠券管理系统</h1>
            </div>
            <nav>
                <ul class="flex space-x-6">
                    <li><a href="#" class="text-primary font-medium">首页</a></li>
                    <li><a href="#" class="text-dark hover:text-primary transition-colors duration-300">优惠券列表</a></li>
                    <li><a href="#" class="text-dark hover:text-primary transition-colors duration-300">活动管理</a></li>
                    <li><a href="#" class="text-dark hover:text-primary transition-colors duration-300">数据分析</a></li>
                </ul>
            </nav>
        </div>
    </header>

    <main>
        <!-- 统计卡片 -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-10">
            <div class="bg-white rounded-xl shadow p-6 transform hover:scale-105 transition-all duration-300">
                <div class="flex justify-between items-start">
                    <div>
                        <p class="text-gray-500 mb-1">总优惠券数</p>
                        <h3 class="text-3xl font-bold text-dark" id="totalCoupons">--</h3>
                    </div>
                    <div class="bg-primary/10 p-3 rounded-lg">
                        <i class="fa fa-ticket text-primary text-xl"></i>
                    </div>
                </div>
                <div class="mt-4 text-sm text-success flex items-center">
                    <i class="fa fa-arrow-up mr-1"></i>
                    <span>12% 较上月</span>
                </div>
            </div>

            <div class="bg-white rounded-xl shadow p-6 transform hover:scale-105 transition-all duration-300">
                <div class="flex justify-between items-start">
                    <div>
                        <p class="text-gray-500 mb-1">已领取数</p>
                        <h3 class="text-3xl font-bold text-dark" id="receivedCoupons">--</h3>
                    </div>
                    <div class="bg-success/10 p-3 rounded-lg">
                        <i class="fa fa-users text-success text-xl"></i>
                    </div>
                </div>
                <div class="mt-4 text-sm text-success flex items-center">
                    <i class="fa fa-arrow-up mr-1"></i>
                    <span>8% 较上月</span>
                </div>
            </div>

            <div class="bg-white rounded-xl shadow p-6 transform hover:scale-105 transition-all duration-300">
                <div class="flex justify-between items-start">
                    <div>
                        <p class="text-gray-500 mb-1">已使用数</p>
                        <h3 class="text-3xl font-bold text-dark" id="usedCoupons">--</h3>
                    </div>
                    <div class="bg-warning/10 p-3 rounded-lg">
                        <i class="fa fa-check-circle text-warning text-xl"></i>
                    </div>
                </div>
                <div class="mt-4 text-sm text-danger flex items-center">
                    <i class="fa fa-arrow-down mr-1"></i>
                    <span>3% 较上月</span>
                </div>
            </div>
        </div>

        <!-- 领取优惠券区域 -->
        <section class="bg-white rounded-xl shadow-lg p-6 mb-10">
            <h2 class="text-xl font-bold mb-6 flex items-center">
                <i class="fa fa-gift text-primary mr-2"></i>
                领取优惠券
            </h2>

            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div class="space-y-4">
                    <div>
                        <label for="userId" class="block text-sm font-medium text-gray-700 mb-1">用户 ID</label>
                        <input type="number" id="userId" placeholder="请输入用户 ID" class="input-field w-full">
                    </div>

                    <div>
                        <label for="couponId" class="block text-sm font-medium text-gray-700 mb-1">优惠券 ID</label>
                        <input type="number" id="couponId" placeholder="请输入优惠券 ID" class="input-field w-full">
                    </div>

                    <div>
                        <label for="activityId" class="block text-sm font-medium text-gray-700 mb-1">活动 ID (可选)</label>
                        <input type="number" id="activityId" placeholder="请输入活动 ID" class="input-field w-full">
                    </div>
                </div>

                <div class="md:col-span-2 flex items-center justify-center">
                    <button onclick="receiveCoupon()" class="btn-primary text-lg px-8 py-3 flex items-center">
                        <i class="fa fa-plus-circle mr-2"></i>
                        立即领取
                    </button>
                </div>
            </div>

            <div id="receiveResult" class="mt-6 p-4 rounded-lg hidden"></div>
        </section>

        <!-- 可用优惠券列表 -->
        <section class="bg-white rounded-xl shadow-lg p-6 mb-10">
            <div class="flex justify-between items-center mb-6">
                <h2 class="text-xl font-bold flex items-center">
                    <i class="fa fa-list-alt text-primary mr-2"></i>
                    可用优惠券列表
                </h2>
                <div class="flex space-x-2">
                    <div class="relative">
                        <input type="text" id="couponSearch" placeholder="搜索优惠券..." class="input-field pl-9 pr-4 py-2 w-64">
                        <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                    </div>
                    <button onclick="refreshCouponList()" class="btn-secondary flex items-center">
                        <i class="fa fa-refresh mr-1"></i>
                        刷新
                    </button>
                </div>
            </div>

            <div id="couponList" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                <!-- 优惠券卡片将通过JS动态生成 -->
                <div class="col-span-full text-center py-12 text-gray-500">
                    <i class="fa fa-spinner fa-spin text-3xl mb-3"></i>
                    <p>加载中...</p>
                </div>
            </div>
        </section>

        <!-- 用户优惠券列表 -->
        <section class="bg-white rounded-xl shadow-lg p-6">
            <div class="flex justify-between items-center mb-6">
                <h2 class="text-xl font-bold flex items-center">
                    <i class="fa fa-user-circle text-primary mr-2"></i>
                    用户优惠券列表
                </h2>
                <div class="flex items-center space-x-4">
                    <div>
                        <label for="viewUserId" class="sr-only">用户 ID</label>
                        <input type="number" id="viewUserId" placeholder="请输入用户 ID" class="input-field">
                    </div>
                    <button onclick="getUserCoupons()" class="btn-primary flex items-center">
                        <i class="fa fa-search mr-1"></i>
                        查看
                    </button>
                </div>
            </div>

            <div id="userCouponsList" class="space-y-4">
                <!-- 用户优惠券将通过JS动态生成 -->
                <div class="col-span-full text-center py-12 text-gray-500">
                    <p>请输入用户 ID 并点击"查看"按钮</p>
                </div>
            </div>
        </section>
    </main>

    <footer class="mt-12 text-center text-gray-500 text-sm">
        <p>© 2025 优惠券管理系统 | 版权所有</p>
    </footer>
</div>

<script>
    // 后端API基础URL
    const baseUrl = 'http://localhost:8080/api';

    // 错误处理函数
    const handleError = (error, elementId) => {
        console.error('请求出错:', error);
        const element = document.getElementById(elementId);
        if (element) {
            element.className = 'mt-6 p-4 rounded-lg bg-danger/10 text-danger';
            element.innerHTML = `<i class="fa fa-exclamation-circle mr-2"></i>请求失败: ${error.message}`;
            setTimeout(() => {
                element.classList.add('hidden');
            }, 5000);
        }
    };

    // 格式化日期函数
    const formatDate = (timestamp) => {
        if (!timestamp) return '未知';
        const date = new Date(timestamp);
        return date.toLocaleDateString('zh-CN');
    };

    // 获取优惠券列表
    const getCouponList = async () => {
        const couponListElement = document.getElementById('couponList');
        couponListElement.innerHTML = `
                <div class="col-span-full text-center py-12 text-gray-500">
                    <i class="fa fa-spinner fa-spin text-3xl mb-3"></i>
                    <p>加载中...</p>
                </div>
            `;

        try {
            const response = await fetch(`${baseUrl}/coupon/list`);
            const coupons = await response.json();

            if (!coupons || coupons.length === 0) {
                couponListElement.innerHTML = `
                        <div class="col-span-full text-center py-12 text-gray-500">
                            <i class="fa fa-inbox mb-3 text-4xl"></i>
                            <p>暂无可用优惠券</p>
                        </div>
                    `;
                return;
            }

            couponListElement.innerHTML = '';
            coupons.forEach(coupon => {
                const card = document.createElement('div');
                card.className = 'coupon-card';

                // 根据优惠券类型设置不同的颜色
                let colorClass = 'from-primary/10 to-primary/20';
                let typeText = '通用券';
                let typeColor = 'bg-primary text-white';

                if (coupon.type === 'DISCOUNT') {
                    colorClass = 'from-secondary/10 to-secondary/20';
                    typeText = '折扣券';
                    typeColor = 'bg-secondary text-white';
                } else if (coupon.type === 'CASH') {
                    colorClass = 'from-success/10 to-success/20';
                    typeText = '现金券';
                    typeColor = 'bg-success text-white';
                }

                card.innerHTML = `
                        <div class="relative overflow-hidden rounded-lg shadow-md">
                            <div class="absolute top-0 right-0 w-24 h-24 bg-primary/5 transform rotate-45 translate-x-10 -translate-y-5"></div>
                            <div class="absolute top-0 right-0 w-24 h-24 bg-primary/10 transform rotate-45 translate-x-10 -translate-y-10"></div>

                            <div class="p-5 relative">
                                <div class="flex justify-between items-start mb-4">
                                    <div class="flex items-center">
                                        <span class="inline-block ${typeColor} px-2 py-1 rounded text-xs font-medium mr-2">${typeText}</span>
                                        <h3 class="font-bold text-lg">${coupon.name}</h3>
                                    </div>
                                    <div class="text-right">
                                        <div class="text-3xl font-bold text-primary">
                                            ${coupon.discountType === 'PERCENTAGE' ? `${coupon.discountValue}折` : `¥${coupon.discountValue}`}
                                        </div>
                                    </div>
                                </div>

                                <div class="mb-4 text-sm text-gray-600">
                                    <p class="mb-1"><i class="fa fa-calendar-o mr-2"></i>有效期: ${formatDate(coupon.startTime)} - ${formatDate(coupon.endTime)}</p>
                                    <p><i class="fa fa-shopping-bag mr-2"></i>适用范围: ${coupon.scope}</p>
                                </div>

                                <div class="flex justify-between items-center pt-4 border-t border-gray-100">
                                    <span class="text-xs text-gray-500">优惠券ID: ${coupon.id}</span>
                                    <button onclick="fillCouponId(${coupon.id})" class="btn-primary text-sm">
                                        领取
                                    </button>
                                </div>
                            </div>
                        </div>
                    `;
                couponListElement.appendChild(card);
            });

            // 更新统计数据
            updateStats(coupons);
        } catch (error) {
            handleError(error, 'couponList');
        }
    };

    // 更新统计数据
    const updateStats = (coupons) => {
        const totalCoupons = coupons.length;
        let receivedCount = 0;
        let usedCount = 0;

        // 这里需要根据实际数据结构调整逻辑
        // 假设优惠券有一个关联的userCoupons字段，包含用户领取信息
        coupons.forEach(coupon => {
            if (coupon.userCoupons && coupon.userCoupons.length) {
                receivedCount += coupon.userCoupons.length;
                usedCount += coupon.userCoupons.filter(uc => uc.status === 'USED').length;
            }
        });

        document.getElementById('totalCoupons').textContent = totalCoupons;
        document.getElementById('receivedCoupons').textContent = receivedCount;
        document.getElementById('usedCoupons').textContent = usedCount;
    };

    // 填充优惠券ID
    const fillCouponId = (id) => {
        document.getElementById('couponId').value = id;
    };

    // 用户领取优惠券
    const receiveCoupon = async () => {
        const userId = document.getElementById('userId').value;
        const couponId = document.getElementById('couponId').value;
        const activityId = document.getElementById('activityId').value || undefined;

        if (!userId || !couponId) {
            const resultElement = document.getElementById('receiveResult');
            resultElement.className = 'mt-6 p-4 rounded-lg bg-warning/10 text-warning';
            resultElement.innerHTML = `<i class="fa fa-exclamation-triangle mr-2"></i>请输入用户ID和优惠券ID`;
            setTimeout(() => {
                resultElement.classList.add('hidden');
            }, 3000);
            return;
        }

        const resultElement = document.getElementById('receiveResult');
        resultElement.innerHTML = `
                <i class="fa fa-spinner fa-spin mr-2"></i>
                正在处理请求...
            `;
        resultElement.className = 'mt-6 p-4 rounded-lg bg-info/10 text-info';
        resultElement.classList.remove('hidden');

        try {
            const response = await fetch(`${baseUrl}/coupon/receive?userId=${userId}&couponId=${couponId}${activityId ? `&activityId=${activityId}` : ''}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            if (!response.ok) {
                throw new Error(`HTTP错误，状态码: ${response.status}`);
            }

            const result = await response.text();

            if (result === 'true') {
                resultElement.className = 'mt-6 p-4 rounded-lg bg-success/10 text-success';
                resultElement.innerHTML = `<i class="fa fa-check-circle mr-2"></i>领取成功！`;

                // 刷新用户优惠券列表
                if (userId === document.getElementById('viewUserId').value) {
                    setTimeout(() => {
                        getUserCoupons();
                    }, 1000);
                }
            } else {
                resultElement.className = 'mt-6 p-4 rounded-lg bg-danger/10 text-danger';
                resultElement.innerHTML = `<i class="fa fa-times-circle mr-2"></i>领取失败！可能已领取或优惠券已过期`;
            }

            // 刷新优惠券列表
            setTimeout(() => {
                getCouponList();
            }, 1500);

        } catch (error) {
            handleError(error, 'receiveResult');
        }

        setTimeout(() => {
            resultElement.classList.add('hidden');
        }, 5000);
    };

    // 查看用户优惠券列表
    const getUserCoupons = async () => {
        const userId = document.getElementById('viewUserId').value;

        if (!userId) {
            const userCouponsList = document.getElementById('userCouponsList');
            userCouponsList.innerHTML = `
                    <div class="col-span-full text-center py-12 text-gray-500">
                        <i class="fa fa-exclamation-circle mb-3 text-3xl"></i>
                        <p>请输入用户ID</p>
                    </div>
                `;
            return;
        }

        const userCouponsList = document.getElementById('userCouponsList');
        userCouponsList.innerHTML = `
                <div class="col-span-full text-center py-12 text-gray-500">
                    <i class="fa fa-spinner fa-spin text-3xl mb-3"></i>
                    <p>加载中...</p>
                </div>
            `;

        try {
            const response = await fetch(`${baseUrl}/coupon/user/${userId}`);
            const userCoupons = await response.json();

            if (!userCoupons || userCoupons.length === 0) {
                userCouponsList.innerHTML = `
                        <div class="col-span-full text-center py-12 text-gray-500">
                            <i class="fa fa-inbox mb-3 text-4xl"></i>
                            <p>该用户暂无优惠券</p>
                        </div>
                    `;
                return;
            }

            userCouponsList.innerHTML = '';
            userCoupons.forEach(coupon => {
                let statusClass = '';
                let statusText = '';

                if (coupon.status === 'UNUSED') {
                    statusClass = 'bg-success/10 text-success';
                    statusText = '未使用';
                } else if (coupon.status === 'USED') {
                    statusClass = 'bg-gray-100 text-gray-500';
                    statusText = '已使用';
                } else if (coupon.status === 'EXPIRED') {
                    statusClass = 'bg-danger/10 text-danger';
                    statusText = '已过期';
                }

                const li = document.createElement('div');
                li.className = 'coupon-card';

                li.innerHTML = `
                        <div class="p-5">
                            <div class="flex justify-between items-start mb-4">
                                <div>
                                    <h3 class="font-bold text-lg">${coupon.couponName}</h3>
                                    <p class="text-sm text-gray-500 mt-1">优惠券码: ${coupon.couponCode}</p>
                                </div>
                                <div class="coupon-status ${statusClass}">${statusText}</div>
                            </div>

                            <div class="grid grid-cols-2 gap-4 text-sm mb-4">
                                <div class="text-gray-600">
                                    <p><i class="fa fa-calendar-o mr-2"></i>领取时间: ${formatDate(coupon.receiveTime)}</p>
                                    <p><i class="fa fa-calendar-check-o mr-2"></i>过期时间: ${formatDate(coupon.expireTime)}</p>
                                </div>
                                <div class="text-gray-600">
                                    <p><i class="fa fa-ticket mr-2"></i>优惠券ID: ${coupon.couponId}</p>
                                    <p><i class="fa fa-user mr-2"></i>用户ID: ${coupon.userId}</p>
                                </div>
                            </div>

                            ${coupon.status === 'UNUSED' ? `
                                <button onclick="useCoupon('${coupon.couponCode}')" class="btn-primary text-sm">
                                    使用优惠券
                                </button>
                            ` : ''}
                        </div>
                    `;
                userCouponsList.appendChild(li);
            });
        } catch (error) {
            handleError(error, 'userCouponsList');
        }
    };

    // 使用优惠券
    const useCoupon = async (couponCode) => {
        if (!confirm('确定要使用这张优惠券吗？')) {
            return;
        }

        try {
            const userId = document.getElementById('viewUserId').value;
            if (!userId) {
                alert('请先输入用户ID查看优惠券列表');
                return;
            }

            const response = await fetch(`${baseUrl}/coupon/use`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    userId: parseInt(userId),
                    couponCode: couponCode
                })
            });

            const result = await response.text();

            if (result === 'true') {
                alert('优惠券使用成功！');
                getUserCoupons(); // 刷新列表
            } else {
                alert('优惠券使用失败！');
            }
        } catch (error) {
            console.error('使用优惠券出错:', error);
            alert('使用优惠券时发生错误: ' + error.message);
        }
    };

    // 刷新优惠券列表
    const refreshCouponList = () => {
        getCouponList();
    };

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', () => {
        getCouponList();
    });
</script>
</body>
</html>
